import { Directive, DirectiveBinding } from 'vue';
import { hasPermi, hasRole, hasRoleType } from '@/utils/permission';

/**
 * 按钮权限
 */
export const hasPermiDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value && value instanceof Array && value.length > 0) {
      const isHasPermi = hasPermi(value);
      if (!isHasPermi) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    }
  }
};

/**
 * 角色权限
 */
export const hasRoleDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value && value instanceof Array && value.length > 0) {
      const isHasRole = hasRole(value);
      if (!isHasRole) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    }
  }
};

/**
 * 角色类型权限校验
 */
export const hasRoleTypeDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value && value instanceof Array && value.length > 0) {
      const isHasRoleType = hasRoleType(value);
      if (!isHasRoleType) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    }
  }
};

/**
 * 阻止事件穿透
 */
export const stopPropagation: Directive = {
  beforeMount(el: HTMLElement) {
    el.addEventListener('click', (event) => {
      event.stopPropagation();
    });
  }
};
